using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections.Generic;

public partial class adm_users : reportPage
{
    private void renderUser(user u, StringBuilder tableBuilder, bool isFailedAttempt)
    {
        tableBuilder.AppendFormat
        (
            "<tr>" +
                "<td>{0}</td>" +
                "<td><input class=txt name=UNM_{0} type=text value=\"{1}\" /></td>" +
                "<td><input class=txt name=PWD_{0} type=text value=\"{2}\" /></td>" +
                "<td><input class=txt name=FNM_{0} type=text value=\"{3}\" /></td>" +
                "<td><input class=txt name=LNM_{0} type=text value=\"{4}\" /></td>" +
                "<td><input name=ACT_{0} type=checkbox {5}></td>" +
                "<td>{6}</td>" +
                "<td><input class=txt name=DLR_{0} type=text value=\"{10}\" /></td>" +
                "<td><input class=txt name=AUT_{0} type=text value=\"{11}\" /></td>" +
                "<td>{7}</td>" +
                "<td>" +
                    "<input type=submit name=SAV_{0} value=\" {8} \" />&nbsp;&nbsp;&nbsp;" +
                    "<input type=submit name=DEL_{0} value=\" Delete \" {9} />&nbsp;&nbsp;&nbsp;" +
                "</td>" +
            "</tr>",
            u.getID(),
            u.getID() == 0 && isFailedAttempt ? base.getString("UNM_0") : u.getUserName(),
            "",
            u.getID() == 0 && isFailedAttempt ? base.getString("FNM_0") : u.getFirstName(),
            u.getID() == 0 && isFailedAttempt ? base.getString("LNM_0") : u.getLastName(),
            u.getID() == 0 && isFailedAttempt ? (base.getString("ACT_0") == "on" ? "checked" : "") : u.getIsActive() ? "checked" : "",
            u.getIsAdministrator() ? "Yes" : "&nbsp;",
            prepareProjectChecks(u),
            u.getID() > 0 ? "Update" : "Insert",
            u.getID() > 0 ? "" : "disabled",
            string.Join(",", u.getDealerCodes()),
            u.getAuthLevel()
        );
    }

    private static string prepareProjectChecks(user u)
    {
        List<string> userProjects = new List<string>(u.getProjects());
        return
            string.Format("<input type='checkbox' name='auth_" + Global.PROJECT_QVN2013 + "_{0}' {1} />QVN |", u.getID(), userProjects.Contains(Global.PROJECT_QVN2013) ? "checked" : "") +
            string.Format("<input type='checkbox' name='auth_" + Global.PROJECT_SATIS_SUREC + "_{0}' {1} />RD |", u.getID(), userProjects.Contains(Global.PROJECT_SATIS_SUREC) ? "checked" : "") +
            string.Format("<input type='checkbox' name='auth_" + Global.PROJECT_SSRD + "_{0}' {1} />SS |", u.getID(), userProjects.Contains(Global.PROJECT_SSRD) ? "checked" : "") +
            string.Format("<input type='checkbox' name='auth_TIC_{0}' {1} />TIC |", u.getID(), userProjects.Contains("TIC") ? "checked" : "") +
            string.Format("<input type='checkbox' name='auth_rec_{0}' {1} />rec", u.getID(), userProjects.Contains("rec") ? "checked" : "");
    }

    private string processCommand()
    {
        string errorMessage = null;

        foreach (string key in Request.Form.AllKeys)
        {
            if (key.StartsWith("SAV_") || key.StartsWith("DEL_"))
            {
                long id = Convert.ToInt64(key.Substring(4));
                user userToUpdate = id == 0 ? user.New() : user.getUserById(id);
                if (userToUpdate == null) return "The user with id " + id + " does not exist in the database";

                if (key.StartsWith("SAV_"))
                {

                    if (string.IsNullOrEmpty(base.getString("UNM_" + id))) return "The user name can not be empty";
                    if (userToUpdate.getUserName() != base.getString("UNM_" + id))
                    {
                        if (!userToUpdate.setUserName(base.getString("UNM_" + id))) return "The user name specified already assigned to another user";
                    }

                    userToUpdate.setFirstName(base.getString("FNM_" + id));
                    userToUpdate.setLastName(base.getString("LNM_" + id));
                    userToUpdate.setActivationStatus(base.getString("ACT_" + id) == "on");

                    List<string> authorizedProjects = new List<string>();
                    if (base.getString("auth_" + Global.PROJECT_QVN2013 + "_" + id) == "on") authorizedProjects.Add(Global.PROJECT_QVN2013);
                    if (base.getString("auth_" + Global.PROJECT_SATIS_SUREC + "_" + id) == "on") authorizedProjects.Add(Global.PROJECT_SATIS_SUREC);
                    if (base.getString("auth_" + Global.PROJECT_SSRD + "_" + id) == "on") authorizedProjects.Add(Global.PROJECT_SSRD);
                    if (base.getString("auth_TIC_" + id) == "on") authorizedProjects.Add("TIC");
                    if (base.getString("auth_rec_" + id) == "on") authorizedProjects.Add("rec");
                    userToUpdate.SetProjects(authorizedProjects.ToArray());

                    if (authorizedProjects.Count == 0)
                    {
                        userToUpdate.setActivationStatus(false);
                        errorMessage = "Because authorizations for all the projects was removed, the user is made inactive";
                    }

                    if (string.IsNullOrEmpty(userToUpdate.getUserName())) return "The user name can not be empty";

                    userToUpdate.setDealerCodes(base.getString("DLR_" + id).Split(','));
                    userToUpdate.SetAuthLevel(base.getString("AUT_" + id));

                    if (string.IsNullOrEmpty(base.getString("PWD_" + id)))
                    {
                        if (id == 0) return "The password should be set when creating a new user";
                    }
                    else
                    {
                        userToUpdate.SetPassword(base.getString("PWD_" + id));
                    }

                    if (id == 0) userToUpdate.Insert(); else userToUpdate.Update();
                    if (!string.IsNullOrEmpty(errorMessage)) return errorMessage;
                }
                else
                {
                    userToUpdate.Remove();
                }
            }
        }
        return "";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        base.initialize();
        base.ensureAdministratorIsLoggedIn();

        if (base.getString("postBack") == "1")
        {
            errorMessage.Text = processCommand();
            if (string.IsNullOrEmpty(errorMessage.Text))
            {
                errorMessage.Text = "Command has been processed successfully";
                successClass.Text = "fine";
            }
            else
            {
                successClass.Text = "err";
            }
        }
        else
        {
            errorMessage.Text = "Ready..";
            successClass.Text = "fine";
        }

        errorMessage.Text = "<br />&nbsp;&nbsp;" + errorMessage.Text + "<br /><br />";

        StringBuilder tableBuilder = new StringBuilder();

        user[] allUsers = user.getAllUsers();

        foreach (user u in allUsers) renderUser(u, tableBuilder, false);

        renderUser(user.New(), tableBuilder, successClass.Text == "err");

        usersTable.Text = tableBuilder.ToString();

    }
}
